let dbUtil = require('db-util')
const uniID = require('uni-id')
let db = uniCloud.database()
let dbCmd = db.command
let $ = dbCmd.aggregate
const md5 = require("md5-node")
const payUtil = require("pay-util")
const uniPay = require("unipay")
const {
	CLOUDURL
} = require('config')
const {
	wxPubConfig
} = require("config");
const WxPubApi = require("wx-public-api")
const wxPubApi = new WxPubApi(wxPubConfig.appId, wxPubConfig.appSecret)
const errParams = {
	errCode: 400,
	errMsg: '参数错误！'
}
const errResNotFound = {
	errCode: 501,
	errMsg: '实体不存在！'
}
const {
	disconnect
} = require('cluster')
module.exports = {
	_before: async function() { // 通用预处理器
		const token = this.getUniIdToken()
		if (!token) {
			throw new Error('未登录')
		}
		const payload = await uniID.checkToken(token)
		let {
			code,
			uid,
			permission
		} = payload
		if (code) {
			throw new Error('未登录')
		}
		this.uid = uid
		if (!permission) {
			permission = await uniID.getPermissionByUid({
				uid
			})
		}

		this.permission = permission
		let roleRes = await uniID.getRoleByUid({
			uid
		})
		if (roleRes.code != 0) {
			throw new Error(roleRes.msg)
		}
		this.roles = roleRes.role
		const methodName = this.getMethodName()
		this.isAdmin = this.roles.some(item => item == 'admin')
		this.isBoss = this.roles.some(item => item == 'boss')
	},


	//获取用户当前门店总礼包余额和优惠券
	async getUserPackage({
		memberId,
		storeId
	}) {
		const {
			sum
		} = db.command.aggregate
		var money = 0;
		var disCountData = [];
		var disCountCancelImg =
			'https://7463-tcb-rxeszamj94676b-6d6j813d8fcf0-1303238310.tcb.qcloud.la/static/img/dikouquan-img.png'
		//总金额
		let packageUserMoney = await db.collection('t3ds-package-user').aggregate()
			.match({
				uid: memberId,
				delFlag: 0,
				type: 0,
				storeIds: dbCmd.in([storeId])
			}).project({
				totalMoney: sum('$packageAmount')
			}).group({
				_id: null,
				total: sum('$totalMoney')
			})
			.end()
		if (packageUserMoney.data.length > 0) {
			money = packageUserMoney.data[0].total
		} else {
			money = 0;
		}
		console.log("packageUserMoney", packageUserMoney.data)
		//总优惠券
		let disCount = await db.collection('t3ds-package-user').aggregate()
			.match({
				uid: memberId,
				delFlag: 0,
				type: 1,
				storeIds: dbCmd.in([storeId])
			}).lookup({
				from: 't3ds-store',
				let: {
					store_id: '$storeId',
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.and([
						$.eq(['$_id', '$$store_id']),
					]))).project({
						createBy: 1,
						name: 1,
						type: 1
					}).done(),
				as: 'storeId',
			}).end()

		console.log("disCount", disCount.data.length)
		var count = 0;
		for (var i = 0; i < disCount.data.length; i++) {
			var disCountList = [];
			for (var j = 0; j < disCount.data[i].discountCoupon.length; j++) {
				if (disCount.data[i].discountCoupon[j].num > 0) {
					disCount.data[i].discountCoupon[j].index = j
					disCount.data[i].discountCoupon[j].onSelect = disCountCancelImg
					disCountList.push(disCount.data[i].discountCoupon[j])
					count += 1;
				}
			}
			let obj = {
				_id: disCount.data[i]._id,
				disCountList: disCountList,
				endTime: disCount.data[i].endTime,
				storeId: disCount.data[i].storeId,
				storeIds: disCount.data[i].storeIds
			}
			disCountData.push(obj);
		}

		var data = {
			money: money,
			disCountList: disCountData,
			disCountCount: count
		}

		return data
	},

	//创建赠送金额礼包
	async createPackageMoney({
		storeIds,
		give,
		amount,
		endTime,
		ratio,
		discountRatio
	}) {
		try {
			let data = {
				storeIds: storeIds,
				storeId: storeIds[0],
				packageTopupAmount: amount,
				packageGiveAmount: give,
				createTime: Date.now(),
				endTime: endTime,
				closeRatio: ratio,
				discountRatio: parseInt(discountRatio),
				type: 0,
				createBy: this.uid
			}
			const info = await dbUtil.insert({
				collection: 't3ds-package',
				data
			})
			return data._id;
		} catch (e) {
			return {
				errCode: 500,
				errMsg: e.message
			}
		}
	},
	//创建优惠券礼包
	async createDisCount({
		storeIds,
		amount,
		endTime,
		disCountList,
		ratio,
		discountRatio,
		give
	}) {
		try {
			let data = {
				storeIds: storeIds,
				storeId: storeIds[0],
				packageTopupAmount: amount,
				discountCoupon: disCountList,
				createTime: Date.now(),
				endTime: endTime,
				closeRatio: ratio,
				type: 1,
				discountRatio: parseInt(discountRatio),
				packageGiveAmount: give,
				createBy: this.uid
			}
			const info = await dbUtil.insert({
				collection: 't3ds-package',
				data
			})
			return data._id;
		} catch (e) {
			return {
				errCode: 500,
				errMsg: e.message
			}
		}
	},
	//核销金额
	async chargeOffMoney({
		amount,
		memberId,
		storeId
	}) {
		console.log("amount", amount)
		console.log("memberId", memberId)
		console.log("storeId", storeId)
		let packageList = await dbUtil.getList({
			collection: 't3ds-package-user',
			where: {
				uid: memberId,
				type: 0,
				delFlag: 0,
				storeIds: dbCmd.in([storeId])
			}
		});

		if (packageList.length == 0) {
			throw new Error("用户现金礼包不存在")
		}
		//结算礼包金额和比例
		var chargeOffAmountList = [];
		//核销日志
		var packageLogList = [];
		let transaction = await db.startTransaction()
		try {
			for (var i = 0; i < packageList.length; i++) {
				if (packageList[i].packageAmount >= amount) {
					var money = packageList[i].packageAmount - amount
					await dbUtil.updateById({
						collection: 't3ds-package-user',
						data: {
							_id: packageList[i]._id,
							packageAmount: money,
							delFlag: money == 0 ? 1 : 0
						},
						transaction
					})
					//结算金额
					var chargeOffAmount = {
						moneyCount: amount,
						packageCloseRatio: packageList[i].closeRatio,
					}
					chargeOffAmountList.push(chargeOffAmount)
					// 日志
					var packageLogInfo = {
						packageUser: packageList[i],
						chargeOffAmount: amount,
					}
					packageLogList.push(packageLogInfo)
					break;

				} else {
					amount = amount - packageList[i].packageAmount
					await dbUtil.updateById({
						collection: 't3ds-package-user',
						data: {
							_id: packageList[i]._id,
							packageAmount: 0,
							delFlag: 1
						},
						transaction
					})
					//结算金额
					var chargeOffAmount = {
						moneyCount: packageList[i].packageAmount,
						packageCloseRatio: packageList[i].closeRatio,
					}
					chargeOffAmountList.push(chargeOffAmount)
					// 日志
					var packageLogInfo = {
						packageUser: packageList[i],
						chargeOffAmount: packageList[i].packageAmount,
					}
					packageLogList.push(packageLogInfo)
				}
			}


			//根据门店查询出商家钱包
			let storeInfo = await dbUtil.getById({
				collection: 't3ds-store',
				id: storeId
			})
			let account = await dbUtil.getOne({
				collection: 't3ds-account',
				where: {
					userId: storeInfo.uid
				}
			})

			//计算总金额，一次写入钱包，日志写入多次
			var balanceCount = account.balance;
			//计算金额结算给商家
			for (var i = 0; i < chargeOffAmountList.length; i++) {
				let count = parseInt(chargeOffAmountList[i].moneyCount * chargeOffAmountList[i]
					.packageCloseRatio /
					100)
				balanceCount += count;
				packageLogList[i].income = count
				//写入日志
				await dbUtil.insert({
					collection: 't3ds-account-log',
					data: {
						accountId: account._id,
						createBy: '系统',
						createTime: Date.now(),
						income: count,
						total: balanceCount,
						tradeType: 15,
						userId: account.userId
					},
					transaction
				})
			}

			//设置金额
			await dbUtil.updateById({
				collection: 't3ds-account',
				data: {
					_id: account._id,
					balance: balanceCount
				},
				transaction
			})


			for (var i = 0; i < packageLogList.length; i++) {
				let logData = {
					uid: packageLogList[i].packageUser.uid,
					storeIds: packageLogList[i].packageUser.storeIds,
					storeId: storeId,
					packageUserId: packageLogList[i].packageUser._id,
					closeRatio: packageLogList[i].packageUser.closeRatio,
					detailType: 0,
					createTime: Date.now(),
					type: 0,
					discountRatio: packageLogList[i].packageUser.discountRatio,
					closeAmount: packageLogList[i].income,
					chargeOffAmount: packageLogList[i].chargeOffAmount
				}
				await dbUtil.insert({
					collection: 't3ds-package-log',
					data: logData,
					transaction
				})
			}
			await transaction.commit()
			return "核销成功"
		} catch (e) {
			console.error(e)
			await transaction.rollback();
			throw e
			//TODO handle the exception
		}





		// let packageInfo = await dbUtil.getOne({
		// 	collection: 't3ds-package-user',
		// 	where: {
		// 		uid: memberId,
		// 		type: 0,
		// 		delFlag: 0,
		// 		storeIds: dbCmd.in([storeId])
		// 	}
		// });
		// if (!packageInfo) {
		// 	throw new Error("用户现金礼包不存在")
		// }
		// if (packageInfo.packageAmount == 0 || packageInfo.packageAmount < amount) {
		// 	throw new Error("用户余额不足")
		// }
		// let transaction = await db.startTransaction()
		// try {
		// 	var money = packageInfo.packageAmount - amount
		// 	console.log("packageInfo.packageAmount", packageInfo.packageInfopackageAmount)
		// 	console.log("amount", amount)
		// 	await dbUtil.updateById({
		// 		collection: 't3ds-package-user',
		// 		data: {
		// 			_id: packageInfo._id,
		// 			packageAmount: money,
		// 			delFlag: money == 0 ? 1 : 0
		// 		},
		// 		transaction
		// 	})
		// 	//结算金额
		// 	let count = 0;
		// 	//计算结算金额给商家
		// 	if (packageInfo.closeRatio != 0) {
		// 		count = parseInt((amount * packageInfo.closeRatio) / 100)
		// 		console.log("2.1amount", amount)
		// 		console.log("2.1closeRatio", packageInfo.closeRatio)
		// 		console.log("2.1count", count)
		// 		let storeInfo = await dbUtil.getById({
		// 			collection: 't3ds-store',
		// 			id: storeId
		// 		})
		// 		console.log("2.2", storeInfo)
		// 		if (!storeInfo) {
		// 			throw new Error("门店不存在")
		// 		}
		// 		let account = await dbUtil.getOne({
		// 			collection: 't3ds-account',
		// 			where: {
		// 				userId: storeInfo.uid
		// 			}
		// 		})
		// 		console.log("2.3", account)
		// 		if (!account) {
		// 			throw new Error("商家钱包不存在")
		// 		}
		// 		let balance = account.balance + count
		// 		console.log("2.4", balance)
		// 		//设置金额
		// 		await dbUtil.updateById({
		// 			collection: 't3ds-account',
		// 			data: {
		// 				_id: account._id,
		// 				balance: balance
		// 			},
		// 			transaction
		// 		})
		// 		//写入日志
		// 		await dbUtil.insert({
		// 			collection: 't3ds-account-log',
		// 			data: {
		// 				accountId: account._id,
		// 				createBy: '系统',
		// 				createTime: Date.now(),
		// 				income: count,
		// 				total: balance,
		// 				tradeType: 15,
		// 				userId: account.userId
		// 			},
		// 			transaction
		// 		})
		// 	}
		// 	console.log("4")
		// 	let logData = {
		// 		uid: packageInfo.uid,
		// 		storeIds: packageInfo.storeIds,
		// 		storeId: storeId,
		// 		packageUserId: packageInfo._id,
		// 		chargeOffAmount: amount,
		// 		closeRatio: packageInfo.closeRatio,
		// 		detailType: 0,
		// 		createTime: Date.now(),
		// 		type: 0,
		// 		discountRatio: packageInfo.discountRatio,
		// 		closeAmount: count
		// 	}
		// 	console.log("5")
		// 	//await dbUtil.insert('t3ds-package-log', logData, transaction)
		// 	await dbUtil.insert({
		// 		collection: 't3ds-package-log',
		// 		data: logData,
		// 		transaction
		// 	})

		// 	await transaction.commit();
		// 	return "核销成功"


		// } catch (e) {
		// 	console.error(e)
		// 	await transaction.rollback()
		// 	throw e
		// }


		// console.log(packageInfo)
	},
	//核销优惠券
	async chargeOffDisCount({
		submitDisCountListIdx,
		memberId,
		storeId
	}) {
		console.log("submitDisCountListIdx", submitDisCountListIdx)
		console.log("memberId", memberId)
		console.log("storeId", storeId)
		var packageIds = []
		for (var i = 0; i < submitDisCountListIdx.length; i++) {
			packageIds.push(submitDisCountListIdx[i]._id);
		}
		if (packageIds.length == 0) {
			throw new Error("请选择优惠券")
		}
		let packageList = await dbUtil.getList({
			collection: 't3ds-package-user',
			where: {
				_id: dbCmd.in(packageIds),
				uid: memberId,
				type: 1,
				delFlag: 0,
				storeIds: dbCmd.in([storeId])
			}
		});
		//结算列表
		var chargeOffAmountList = []
		var packageLogList = []
		let transaction = await db.startTransaction()

		try {
			//遍历结果，减优惠券数量
			for (var i = 0; i < submitDisCountListIdx.length; i++) {
				var money = 0
				var disCountList = []
				for (var k = 0; k < packageList.length; k++) {
					if (submitDisCountListIdx[i]._id == packageList[k]._id) {
						for (var j = 0; j < submitDisCountListIdx[i].disCountIdx.length; j++) {
							//优惠券下标
							var idx = submitDisCountListIdx[i].disCountIdx[j].index
							if (packageList[k].discountCoupon[idx].num > 0) {
								//记录消费金额
								money += packageList[k].discountCoupon[idx].money
								packageList[k].discountCoupon[idx].num -= 1
								//记录消费优惠券 
								var coupon = {
									desc: packageList[k].discountCoupon[idx].desc,
									money: packageList[k].discountCoupon[idx].money,
									num: 1
								}
								disCountList.push(coupon)

							} else {
								throw new Error("核销失败，优惠券数量为0")
							}
						}
						var packageUser = packageList[k]
						var data = {
							_id: packageUser._id,
							discountCoupon: packageUser.discountCoupon
						}
						let flag = true;
						for (var e = 0; e < packageUser.discountCoupon.length; e++) {
							if (packageUser.discountCoupon[e].num > 0) {
								flag = false;
								break;
							}
						}
						if (flag) {
							data.delFlag = 1;
						}
						dbUtil.updateById({
							collection: 't3ds-package-user',
							data: data,
							transaction
						});


						//结算金额
						var chargeOffAmount = {
							moneyCount: money,
							packageCloseRatio: packageList[k].closeRatio,
						}
						chargeOffAmountList.push(chargeOffAmount)
						// 日志
						var packageLogInfo = {
							packageUser: packageList[k],
							disCountList: disCountList,
							chargeOffAmount: money,
						}
						packageLogList.push(packageLogInfo)
					}
				}

			}


			//根据门店查询出商家钱包
			let storeInfo = await dbUtil.getById({
				collection: 't3ds-store',
				id: storeId
			})
			let account = await dbUtil.getOne({
				collection: 't3ds-account',
				where: {
					userId: storeInfo.uid
				}
			})

			//计算总金额，一次写入钱包，日志写入多次
			var balanceCount = account.balance;
			//计算金额结算给商家
			for (var i = 0; i < chargeOffAmountList.length; i++) {
				let count = parseInt(chargeOffAmountList[i].moneyCount * chargeOffAmountList[i]
					.packageCloseRatio /
					100)
				balanceCount += count;
				packageLogList[i].income = count
				//写入日志
				await dbUtil.insert({
					collection: 't3ds-account-log',
					data: {
						accountId: account._id,
						createBy: '系统',
						createTime: Date.now(),
						income: count,
						total: balanceCount,
						tradeType: 15,
						userId: account.userId
					},
					transaction
				})
			}

			//设置金额
			await dbUtil.updateById({
				collection: 't3ds-account',
				data: {
					_id: account._id,
					balance: balanceCount
				},
				transaction
			})


			for (var i = 0; i < packageLogList.length; i++) {
				let logData = {
					uid: packageLogList[i].packageUser.uid,
					storeIds: packageLogList[i].packageUser.storeIds,
					storeId: storeId,
					packageUserId: packageLogList[i].packageUser._id,
					discountCoupon: packageLogList[i].disCountList,
					closeRatio: packageLogList[i].packageUser.closeRatio,
					detailType: 0,
					createTime: Date.now(),
					type: 1,
					discountRatio: packageLogList[i].packageUser.discountRatio,
					closeAmount: packageLogList[i].income,
					chargeOffAmount: packageLogList[i].chargeOffAmount
				}
				await dbUtil.insert({
					collection: 't3ds-package-log',
					data: logData,
					transaction
				})
			}
			await transaction.commit();
			return "核销成功"
		} catch (e) {
			console.error(e)
			await transaction.rollback()
			throw e
			//TODO handle the exception
		}





		//console.log(packageList)


		// let disCountLogList = []




		// for (var i = 0; i < submitDisCountListIdx.length; i++) {
		// 	let disCountInfo = packageInfo.discountCoupon[submitDisCountListIdx[i]]
		// 	if (disCountInfo.num >= 1) {
		// 		disCountInfo.num = disCountInfo.num - 1
		// 		let disCountLogInfo = {
		// 			money: disCountInfo.money,
		// 			num: 1,
		// 			desc: disCountInfo.desc
		// 		}
		// 		disCountLogList.push(disCountLogInfo)
		// 	} else {
		// 		break;
		// 		throw new Error("优惠券扣减失败!请重试")
		// 		return
		// 	}
		// 	packageInfo.discountCoupon[submitDisCountListIdx[i]] = disCountInfo
		// }
		// console.log("1")
		// let transaction = await db.startTransaction()
		// try {
		// 	await dbUtil.updateById({
		// 		collection: 't3ds-package-user',
		// 		data: {
		// 			_id: packageInfo._id,
		// 			discountCoupon: packageInfo.discountCoupon
		// 		},
		// 		transaction
		// 	})
		// 	//结算金额
		// 	let count = 0;
		// 	//核销优惠券总金额
		// 	let money = 0;
		// 	//计算结算金额给商家
		// 	if (packageInfo.closeRatio != 0) {
		// 		for (var i = 0; i < disCountLogList.length; i++) {
		// 			money += disCountLogList[i].money;
		// 		}
		// 		count = parseInt((money * packageInfo.closeRatio) / 100)
		// 		let storeInfo = await dbUtil.getById({
		// 			collection: 't3ds-store',
		// 			id: storeId
		// 		})
		// 		if (!storeInfo) {
		// 			throw new Error("门店不存在")
		// 		}
		// 		let account = await dbUtil.getOne({
		// 			collection: 't3ds-account',
		// 			where: {
		// 				userId: storeInfo.uid
		// 			}
		// 		})
		// 		if (!account) {
		// 			throw new Error("商家钱包不存在")
		// 		}
		// 		let balance = account.balance + count
		// 		//设置金额
		// 		await dbUtil.updateById({
		// 			collection: 't3ds-account',
		// 			data: {
		// 				_id: account._id,
		// 				balance: balance
		// 			},
		// 			transaction
		// 		})

		// 		//写入日志
		// 		await dbUtil.insert({
		// 			collection: 't3ds-account-log',
		// 			data: {
		// 				accountId: account._id,
		// 				createBy: '系统',
		// 				createTime: Date.now(),
		// 				income: count,
		// 				total: balance,
		// 				tradeType: 15,
		// 				userId: account.userId
		// 			},
		// 			transaction
		// 		})
		// 	}
		// 	let logData = {
		// 		uid: packageInfo.uid,
		// 		storeIds: packageInfo.storeIds,
		// 		storeId: storeId,
		// 		packageUserId: packageInfo._id,
		// 		discountCoupon: disCountLogList,
		// 		closeRatio: packageInfo.closeRatio,
		// 		detailType: 0,
		// 		createTime: Date.now(),
		// 		type: 1,
		// 		discountRatio: packageInfo.discountRatio,
		// 		closeAmount: count,
		// 		chargeOffAmount: money
		// 	}
		// 	//await dbUtil.insert('t3ds-package-log', logData, transaction)
		// 	await dbUtil.insert({
		// 		collection: 't3ds-package-log',
		// 		data: logData,
		// 		transaction

		// 	})
		// 	//判断是否全部优惠券数量都为0了
		// 	let temp = true;
		// 	for (var i = 0; i < packageInfo.discountCoupon.length; i++) {
		// 		if (packageInfo.discountCoupon[i].num > 0) {
		// 			temp = false;
		// 			break;
		// 		}
		// 	}
		// 	//优惠券数量全部为0了，就删掉当前礼包
		// 	if (temp) {
		// 		await dbUtil.updateById({
		// 			collection: 't3ds-package-user',
		// 			data: {
		// 				_id: packageInfo._id,
		// 				delFlag: 0
		// 			},
		// 			transaction
		// 		})
		// 	}

		// 	await transaction.commit();
		// 	return "核销成功"
		// } catch (e) {
		// 	console.error(e)
		// 	await transaction.rollback()
		// 	throw e
		// 	//TODO handle the exception
		// }
	}
}